﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace HostsEditor
{
    public class Host
    {
        // positions                                 12       3                      4      5  6
        public const string SearchExpression = @"^\s*((\#*)\s*(\d+\.\d+\.\d+\.\d+)\s+(.*?))?(\#(.*))?$";
        public const int Search_TheHostRecord = 1;
        public const int Search_EnabledFlag = 2;
        public const int Search_IPAddress = 3;
        public const int Search_HostName = 4;
        public const int Search_Comment = 5;
        public const int Search_CommentText = 6;

        public Host(bool Enabled, string IP, string Host, string Comment)
        {
            enabled = Enabled;
            ip = IP;
            host = Host;
            comment = Comment;
        }
        public Host(string Comment)
        {
            enabled = false;
            ip = null;
            host = null;
            comment = Comment;
        }

        private string comment;
        public string Comment
        {
            get { return comment; }
            set { comment = value; }
        }

        bool enabled;
        public bool Enabled
        {
            get { return enabled; }
            set { enabled = value; }
        }

        private string ip;
        public string IP
        {
            get { return ip; }
            set { ip = value; }
        }

        private string host;
        public string HostName
        {
            get { return host; }
            set { host = value; }
        }

        public bool IsEmpty
        {
            get
            {
                return string.IsNullOrEmpty(IP) || string.IsNullOrEmpty(HostName);
            }
        }

        public bool IsComment
        {
            get
            {
                return string.IsNullOrEmpty(IP) && string.IsNullOrEmpty(HostName) && !string.IsNullOrEmpty(comment);
            }
        }

        public override string ToString()
        {
            if (IsComment) return Comment;
            return string.Format("{0}{1}\t{2}{3}", Enabled ? "" : "#", IP, HostName, (string.IsNullOrEmpty(Comment)) ? string.Empty : string.Format("\t#{0}", Comment));
        }

        public static Host Parse(string record)
        {
            Match match = Regex.Match(record, @"^\s*((\#*)\s*(\d+\.\d+\.\d+\.\d+)\s+(.*?))?(\#(.*))?$", RegexOptions.Compiled);
            string comment = match.Groups[Host.Search_Comment].Value.Trim();

            return new Host(
                            match.Groups[Host.Search_EnabledFlag].Length == 0,
                            match.Groups[Host.Search_IPAddress].Value.Trim(),
                            match.Groups[Host.Search_HostName].Value.Trim(),
                            (comment.Length > 1) ? comment.Substring(1) : comment);
        }
    }
}
